<template>
  <div class="container">
    <!-- 轨迹 -->
    <div style="display: flex; height: 100%">
      <el-collapse-transition name="el-zoom-in-left">
        <div v-show="leftShow" class="left">
          <Tree @chooseDate="chooseDate" @historyInfo="historyInfo" />
          <div @click="leftShow = !leftShow" class="leftBtn">
            <i class="el-icon-arrow-left"></i>
          </div>
        </div>
      </el-collapse-transition>
      <!-- 地图容器 -->
      <div
        class="mapBox"
        :class="{
          leftShow: leftShow == false,
          bottomShow: bottomShow == false,
        }"
        style="position: relative"
      >
        <!-- 地图 -->
        <div
          id="gdMap"
          style="height: 100%; width: 100%"
          v-if="nowMap == 1"
        ></div>

        <div style="height: 100%; width: 100%" v-if="nowMap == 2">
          <TMapTrack
            ref="wolrdmap"
            :sContent="$refs.pop"
            style="height: 100%; width: 100%"
          ></TMapTrack>
        </div>

        <div style="position: absolute; left: 10px; bottom: 50px; z-index: 999">
          <el-button size="mini" @click="mapchoose(1)">高德地图</el-button>
          <div style="margin: 2px 0"></div>
          <el-button size="mini" @click="mapchoose(2)">天地图</el-button>
        </div>

        <div class="btnBox" style="align-items: center" v-if="nowMap == 1">
          <div @click="start()" class="btn">开始</div>
          <div @click="pause()" class="btn" v-if="trackStatus != 'STOP_MOVE'">
            暂停
          </div>
          <div @click="resume()" class="btn" v-if="trackStatus != 'STOP_MOVE'">
            继续
          </div>
          <div @click="stop()" class="btn">停止</div>
          <div style="margin: 0 6px">
            <el-slider
              v-model="speed"
              style="width: 200px"
              :min="1"
              :max="5000"
              @change="speedChange"
            ></el-slider>
          </div>
        </div>
      </div>
    </div>

    <el-collapse-transition name="el-zoom-in-bottom">
      <div v-show="bottomShow" class="bottom">
        <Table
          ref="tabellist"
          :chooseDateVal="chooseDateVal"
          @timeSearchInfo="timeSearchInfo"
        ></Table>

        <div @click="bottomShow = !bottomShow" class="btnBox">
          <i class="el-icon-arrow-down"></i>
        </div>
      </div>
    </el-collapse-transition>

    <!-- 左侧隐藏后显示的按钮 -->
    <div
      @click="leftShow = !leftShow"
      v-if="leftShow == false"
      class="leftshowBtn flex-cener"
    >
      <span class="el-icon-arrow-right"></span>
    </div>

    <!-- 下面列表隐藏后显示的按钮 -->
    <div
      @click="bottomShow = !bottomShow"
      v-if="bottomShow == false"
      class="bottomBtn flex-cener"
    >
      <span class="el-icon-arrow-up"></span>
    </div>

    <!-- 地图打点弹窗 -->
    <div
      class="markerStyle"
      :style="{ width: popdata.showde ? '400px' : '170px' }"
      ref="pop"
    >
      <div class="markerStyleLeft">
        <p style="margin: 0">车牌：{{ popdata.hbCarNo }}</p>
        <p style="margin: 0">时间：{{ popdata.gpsDateTime }}</p>
        <div v-show="popdata.labelType == 0">
          <p>类型：{{ popdata.dvcLevelTwoName }}</p>
          <p>品牌：{{ popdata.brandName }}</p>
          <p>型号：{{ popdata.modelName }}</p>
        </div>
        <p>ACC：{{ popdata.accStateDesc }}</p>
        <p>速度：{{ popdata.speed }}(km/h)</p>
        <p>油量：{{ popdata.oil }}</p>
        <p>里程：{{ popdata.mileage }}</p>
        <p>位置：{{ popdata.curAddress }}</p>
        <div class="btns">
          <div
            @click="trajectory()"
            style="width: 40px; margin: 0 anto; cursor: pointer"
          >
            <i class="el-icon-location-information fz22"></i>
            <p>轨迹</p>
          </div>
          <div
            @click="track()"
            style="width: 40px; margin: 0 anto; cursor: pointer"
          >
            <i class="el-icon-position fz22"></i>
            <p>跟踪</p>
          </div>
          <div
            @click="video()"
            style="width: 40px; margin: 0 anto; cursor: pointer"
          >
            <i class="el-icon-video-camera fz22"></i>
            <p>视频</p>
          </div>
          <div
            style="width: 40px; margin: 0 anto; cursor: pointer"
            id="showMore"
            @click="
              popdata.showde
                ? (popdata.showde = false)
                : (popdata.showde = true);
              $forceUpdate();
            "
            v-show="popdata.labelType == 0"
          >
            <i class="el-icon-arrow-right fz24 mt20"></i>
          </div>
        </div>
      </div>
      <div class="markerStyleRight" v-show="popdata.showde">
        <p>车 主：{{ popdata.ownerName }}</p>
        <p>车主电话：{{ popdata.ownerContact }}</p>
        <p>驾驶员：{{ popdata.driverName }}</p>
        <p>驾驶员电话：{{ popdata.driverContact }}</p>
        <p>操作证号：{{ popdata.driverCert }}</p>
        <p>发证机构：{{ popdata.certOrg }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import Tree from "./tree.vue";
import Table from "./table.vue";
import api from "@/api/location/track";
import TMapTrack from "../../../components/WorldMap/tmapTrack.vue";
export default {
  components: {
    Table,
    Tree,
    TMapTrack,
  },
  data() {
    return {
      leftShow: true,
      bottomShow: true,
      isCompany: false,
      popdata: { show: false, labelType: 0, showde: false },
      allCarNum: [],
      notWorkNum: [],
      notWorkOtherNum: [],
      workNum: [],

      chooseDateVal: "",
      nowMap: 1,
      speed: 500, //ms
      trackStatus: "",
    };
  },
  mounted() {
    this.initmap();
  },
  methods: {
    speedChange() {
      this.marker.stopMove();
      this.marker.moveAlong(this.lineArr, {
        duration: this.speed,
        autoRotation: true,
      });
      this.trackStatus = "START";
    },
    initmap() {
      this.map = new AMap.Map("gdMap", {
        //设置地图容器id
        viewMode: "3D", //是否为3D地图模式
        zoom: 13, //初始化地图级别
        center: [104.10194, 30.65984], //初始化地图中心点位置
      });

      let toolBar = new AMap.ToolBar({
        position: {
          top: "110px",
          right: "40px",
        },
      });
      let controlBar = new AMap.ControlBar({
        position: {
          top: "10px",
          right: "10px",
        },
      });
      this.map.addControl(new AMap.Scale());
      this.map.addControl(toolBar);
      this.map.addControl(controlBar);
      this.map.setDefaultCursor("pointer");

      // this.setClusterMraker();
      // this.setMapline();
    },
    historyInfo(val) {
      console.log("======接收值", val);
      this.configId = val;
    },
    chooseDate(val) {
      console.log("treeto======接收时间", val);
      this.chooseDateVal = val;
    },
    //获取时间段
    timeSearchInfo(val) {
      console.log(val);
      // this.MAps.amap.clearMap();
      if (!this.configId) {
        return this.$message.warning("请先选择车辆");
      }
      this.lineArr = [];
      let obj = {
        configId: this.configId,
        startTime: val.startDate,
        endTime: val.endDate,
      };
      console.log(obj);

      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      api
        .trackData(obj)
        .then((res) => {
          loading.close();
          if ((res.code = 200)) {
            let data = res.data;
            let obj = {
              table: data,
              configId: this.configId,
            };
            this.$refs.tabellist.getData(obj);

            this.getline(data);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          loading.close();
        });
    },

    setClusterMraker() {
      console.log(1112);
      let arr = [
        {
          lnglat: [104.10194, 30.65984],
          extData: { carNo: "1213", name: "张三" },
        },
        {
          lnglat: [104.1018, 30.65984],
          extData: { carNo: "1214", name: "李四" },
        },
        {
          lnglat: [104.09, 30.65984],
          extData: { carNo: "1214", name: "李四" },
        },
        {
          lnglat: [104.08, 30.65984],
          extData: { carNo: "1214", name: "李四" },
        },
      ];
      if (this.markerClusterer) {
        this.markerClusterer.setMap(null);
      }
      // 此处为点聚合
      this.markerClusterer = new AMap.MarkerCluster(this.map, arr, {
        gridSize: 100,
        // renderClusterMarker: renderClusterMarker, // 自定义聚合点样式
        renderMarker: this.renderMarker, // 自定义非聚合点样式
      });

      //添加聚合点点击事件
      this.markerClusterer.on("click", (data) => {
        console.log(data);
        let canBoost = false;
        //判断是否是聚合点，不是聚合点就执行单个点击方式
        if (data.clusterData.length > 1) {
          canBoost = true;
        } else {
          data.clusterData.forEach((item) => {
            if (item._amapMarker.count > 1) {
              canBoost = true;
            }
            return;
          });
        }

        //计算所有聚合点的中心点
        let alng = 0,
          alat = 0;
        for (const m of data.clusterData) {
          alng += m.lnglat.lng;
          alat += m.lnglat.lat;
        }
        const lat = alat / data.clusterData.length;
        const lng = alng / data.clusterData.length;
        //以中心点固定倍数放大地图，达到展开聚合点的效果
        if (canBoost) {
          let level = this.map.getZoom();
          this.map.setZoom(level + 2);
          this.map.setCenter([lng, lat]);
        }
      });
    },

    renderMarker(context) {
      const marker = context.marker;
      const item = context.data[0].extData;
      // item.defaultIcon
      let icon = new AMap.Icon({
        image:
          "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
        size: new AMap.Size(24, 24),
        imageSize: new AMap.Size(24, 24),
      });
      let label = {
        content:
          "<div style='height:14px;padding:2px;border:1px solod blue;'><span style='background:#f39c12;color:#fff;'>" +
          item["carNo"] +
          "</span></div>",
        offset: new AMap.Pixel(0, -10),
        direction: "top",
      };

      marker.setIcon(icon);
      marker.setLabel(label);

      // 给点添加点击事件
      let that = this;
      marker.on("click", (e) => {
        console.log(e, item);

        let infoWindow = new AMap.InfoWindow({
          isCustom: true, //使用自定义窗体
          autoMove: true,
          closeWhenClickMap: true,
          content: that.$refs.pop,
          size: new AMap.Size(12, 12),
          offset: new AMap.Pixel(16, -45),
          // position: marker.getPosition(),
          retainWhenClose: true,
        });

        infoWindow.open(this.map, e.target.getPosition());
      });
    },
    getline(data) {
      if (data == undefined || data.length == 0) {
        this.$message.warning("暂无轨迹数据");
        this.map.clearMap();
        return;
      }

      if (this.nowMap == 1) {
        let arr = data.map((item) => {
          return [item.gdLng, item.gdLat];
        });
        // console.log(arr, "===");
        if (this.marker && this.trackStatus == "START") {
          this.marker.stopMove();
        }
        this.trackStatus = "";
        this.setMapline(arr);
      } else if (this.nowMap == 2) {
        let arr = data.map((item) => {
          return { lng: item.lng, lat: item.lat };
        });
        console.log(arr, "===");
        // this.setMapline(arr);
        this.$refs.wolrdmap.TmapSetTravel(arr);
      }
    },
    setMapline(val) {
      this.map.clearMap();
      this.marker = new AMap.Marker({
        map: this.map,
        position: val ? val[0] : [104.10194, 30.65984],
        icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
        offset: new AMap.Pixel(-13, -26),
      });

      this.lineArr = [
        [104.10194, 30.65984],
        [104.1018, 30.65975],
        [104.1017, 30.65972],
        [104.1017, 30.65965],
        [104.1015, 30.6596],
        [104.1014, 30.65954],
        [104.1013, 30.65932],
        [104.1012, 30.659802],
      ];
      this.lineArr = val;

      // 绘制轨迹
      this.polyline = new AMap.Polyline({
        map: this.map,
        path: this.lineArr,
        showDir: true,
        strokeColor: "#28F", //线颜色
        strokeWeight: 6, //线宽
        lineJoin: "round",
        // strokeOpacity: 1,     //线透明度
        // strokeStyle: "solid"  //线样式
      });

      this.passedPolyline = new AMap.Polyline({
        map: this.map,
        strokeColor: "#AF5", //线颜色
        strokeWeight: 6, //线宽
        lineJoin: "round",
      });

      this.marker.on("moving", (e) => {
        this.passedPolyline.setPath(e.passedPath);
        this.map.setCenter(e.target.getPosition(), true);
        // //获取已经经过点的长度
        // this.passedLineLength = e.passedPath.length;
        // //已经经过的点
        // this.havePassedLine = e.passedPath;
        // console.log("==?", this.passedLineLength);
        // console.log("==havePassedLine", this.havePassedLine);
      });
      this.map.setFitView();
    },
    // 开始
    start() {
      if (!this.marker) {
        this.$message.warning("暂无轨迹");
        return false;
      }
      if (this.trackStatus == "START") {
        this.$message.warning("已开始行程");
        return false;
      }
      this.$message.success("开始行程");
      this.marker.moveAlong(this.lineArr, {
        // 每一段的时长(ms)
        // duration: 500, //可根据实际采集时间间隔设置
        duration: this.speed, //可根据实际采集时间间隔设置
        // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
        autoRotation: true,
      });
      this.trackStatus = "START";
    },
    // 暂停
    pause() {
      if (!this.marker) {
        this.$message.warning("暂无轨迹");
        return false;
      }
      if (this.trackStatus == "PAUSE_MOVE") {
        this.$message.warning("已暂停行程");
        return false;
      }
      this.$message.success("暂停行程");
      this.marker.pauseMove();
      this.trackStatus = "PAUSE_MOVE";
    },
    // 继续
    resume() {
      if (!this.marker) {
        this.$message.warning("暂无轨迹");
        return false;
      }
      if (this.trackStatus == "START" || this.trackStatus == "RESUME_MOVE") {
        this.$message.warning("正在行程中");
        return false;
      }

      this.$message.success("继续行程");
      this.marker.resumeMove();
      this.trackStatus = "RESUME_MOVE";
    },
    // 停止
    stop() {
      if (!this.marker) {
        this.$message.warning("暂无轨迹");
        return false;
      }
      this.trackStatus = "STOP_MOVE";
      this.$message.success("停止行程");
      this.marker.stopMove();
    },
    // 地图选择
    mapchoose(val) {
      this.nowMap = val;
      this.$refs.tabellist.getData([]);
      if (val == 1) {
        this.map.clearMap();
        this.$refs.wolrdmap.clearTrack();
      } else if (val == 2) {
        if (this.marker) {
          this.marker.stopMove();
        }
      }
    },
    carFrame(val) {
      console.log("====地图传出===>", val);
      this.popdata = val;
      // this.popdata.show = true;
    },
  },
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}
.container {
  height: calc(100vh - 80px);
  width: 100%;
  .left {
    width: 300px;
    height: 64%;
    // background: #ccc;
    position: relative;
    .leftBtn {
      width: 40px;
      height: 20px;
      position: absolute;
      top: 10px;
      right: 20px;
      z-index: 1;
    }
  }
  .bottom {
    height: calc(36% - 10px);
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0px;
    // border: 1px solid red;
    // background: #ccc;
    // z-index: 1;
    .btnBox {
      position: absolute;
      right: 15px;
      top: 10px;
    }
  }
  .bottomBtn {
    height: 30px;
    width: 30px;
    background: #fff;
    border-radius: 4px;
    position: absolute;
    bottom: 20px;
    right: 20px;
    z-index: 999;
  }
  .leftshowBtn {
    height: 30px;
    width: 30px;
    background: #fff;
    border-radius: 4px;
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 999;
  }
  .mapBox {
    height: 64%;
    width: calc(100% - 300px);
  }
  .btnBox {
    position: absolute;
    right: 40px;
    bottom: 20px;
    z-index: 999;
    padding: 4px 18px;
    display: flex;
    .btn {
      background: #409eff;
      color: #fff;
      font-size: 12px;
      width: 60px;
      height: 30px;
      margin-right: 10px;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
  }
  .mapBox.leftShow {
    width: 100%;
  }
  .mapBox.bottomShow {
    height: 100%;
  }
  .mapBox.leftShow.bottomShow {
    width: 100%;
    height: 100%;
  }
  .markerStyle {
    display: flex;
    font-size: 12px;
    background: #ebe9e5;
    padding: 15px 12px !important;
    line-height: 18px !important;
    border-radius: 5px;
    box-shadow: 1px 3px 8px #555 !important;
    .btns {
      display: flex;
      .fz22 {
        font-size: 22px;
      }
    }
  }
}
.flex-cener {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
